//
// Created by Administrator on 2021/6/1.
//
#include <vector>
#include <iostream>

using namespace std;

//Definition for a binary tree node.
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr) {}

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
private:
    int ans = 0;
public:
    int distributeCoins(TreeNode *root) {
        dfs(root);
        return ans;
    }

    int dfs(TreeNode *root) {
        // dfs里啥意思？
        // 一个后序遍历
        if (root == nullptr) return 0;
        int L = dfs(root->left);
        int R = dfs(root->right);
        ans += abs(L) + abs(R);
        return root->val + L + R - 1; // 过载量 这个节点  超出1个金币的个数  可以是负数
        // 负数表示要从父节点移入  正数表示要移动到其他节点
    }
};

int main() {
    auto n1 = TreeNode(3), n2 = TreeNode(0), n3 = TreeNode(0);
    n1.left = &n2;
    n1.right = &n3;
    Solution sol;
    cout << sol.distributeCoins(&n1) << endl;
    return 0;
}